#!usr/bin/node

const http = require('http'),
      items = [];

function genPage() {
  let html = `
      <!DOCTYPE html>
      <html>
        <head>
          <meta charset="utf-8" />
          <title>todo list</title>
        </head>
        <body>
          <h1>Todo List</h1>
          <form method='GET' action='/'>
            <input type='text' name='item'>
            <input type='submit' value='submit'>
          </form>
          <ul>%</ul>
        </body>
      </html>`;
  const dom = items.map(item => `<li>${item}</li>`).join('');

  html = html.replace('%',dom);
  return html;
}

http.createServer((req,res) => {
  //get pathname
  const url = new URL(req.url,`http://${req.headers.host}`),
        pathname = url.pathname,
        item = url.searchParams.get('item');

  if(pathname === '/') {
    if(item !== null && item !== '') {
      items.push(item);
    }
    res.end(genPage());
  }else {
    res.statusCode = 404;
    res.end('Resource not found');
  }
}).listen(8080);

